import { Injectable } from '@angular/core';
import {Http,Headers} from "@angular/http";
import "rxjs/Rx";
import {Observable} from "rxjs/Observable";


@Injectable()
export class HttpService {

  constructor(
    private http : Http
  ) { }
  //获取数据请求
  httpGet(url,params):Observable<any>{
    console.log("调用get请求");
    let body = this.encodeParams(params);
    return this.http.get(url,{search:params}).map(res => res.json())
  }

  // httpGetPromist(url,params):Observable<any>{
  //   return this.http.get(url,{search:params})
  //     .toPromise(resolve,reject)
  //     .then((res)=>resolve(res))
  //
  // }

  public headers = new Headers({ 'Content-Type': 'application/json' }); //其实不表明 json 也可以, ng 默认好像是 json
  // public options = new RequestOptions({ headers: this.headers });
  encodeParams(params:Object){
    return Object.keys(params)
      .filter(key => params[key])
      .reduce((sum:URLSearchParams,key:string) =>{
        sum.append(key,params[key]);
        return sum
      },new URLSearchParams)

  }
  //传递数据请求
  httpPost(url,params){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json' );
    headers.append('Access-Control-Allow-Credentials', 'true');
    let body = this.encodeParams(params).toString();
    let newurl =url+'?'+body;
    // console.log(newurl);
    return this.http.post(url,params,{headers:this.headers})
      .map((res)=>res.json())
      .catch((err:Response) => {
        return Observable.throw(err);
      })
  }
  //更新请求
  httpPut(url,params){
    let body = this.encodeParams(params).toString();
    let newurl = url +'?'+body;
    return this.http.put(url,params,{headers:this.headers})
      .map((res) =>res.json())
      .catch((err:Response) => {
        return Observable.throw(err);
    })
  }
  httpDelete(url,params){
    console.log("调用删除");
    let body = this.encodeParams(params).toString();
    let newurl = url + "?" +body;
    return this.http.delete(newurl)
      .map(res => res.json())
      .catch((err:Response) =>{
      return Observable.throw(err)
      })
  }
}


